#! /usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import timedelta

from flask import Blueprint
from flask import render_template, url_for, redirect, flash
from flask_login import login_user, logout_user, login_required

from app.auth.forms import LoginForm
from app.models import User

bp = Blueprint(
    'auth', __name__, template_folder='templates', static_folder='static')


@bp.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and user.verify_password(form.password.data):
            login_user(user, remember=False, force=False, fresh=False)
            return redirect(url_for('users.preloan_index'))
        else:
            flash(category='danger', message=u'用户不存在活密码错误')
            form.username.data = ""
            form.password.data = ""
        return render_template('auth/login.html', form=form)
    return render_template('auth/login.html', form=form)


@bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))
